<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Common\Behavior;
use Think\Behavior;

class WebAccessBehavior extends Behavior
{

    CONST SESSION_KEY = 'WEB_ACCESS';

    public function run (&$content)
    {
        // chrome 插件请求
        if (isset($_GET['s']) && $_GET['s'] == 'web_access.php')
        {
            return $this->_auth();
        }
        
        // Admin 模块检查 web access 权限
        if (MODULE_NAME != 'Admin' || ! WEB_ACCESS)
        {
            return true;
        }
        
        return $_SESSION[self::SESSION_KEY];
    }

    /**
     * 检查认证信息, 并跳转
     */
    protected function _auth ()
    {
        foreach ($_SERVER as $_k => $_v)
        {
            if (strpos($_k, 'HTTP_WA') !== false && $_v === md5($_k . C('DATA_AUTH_KEY')))
            {
                \KCSLog::APP('Web access 认证成功');
                $_SESSION[self::SESSION_KEY] = date('Y-m-d H:i:s');
                header('Location:/' . ADMIN_ALIAS);
                exit();
            }
        }
        
        \KCSLog::WARN('Web access 认证失败');
        header('HTTP/1.1 444 Not Found');
        header('Status:444 Not Found');
        exit();
    }
}